import { request } from "./request.js";


export function wechatPay(payload,callback) {
  // 防止重复点击
  if (this.data.isLoading) {
    console.log("isLoading")
    return;
  }

  // 设置加载状态
  this.setData({
    isLoading: true,
  });

  // 显示加载提示
  wx.showLoading({
    title: "正在创建订单...",
    mask: true,
  });

  // 参数校验，确保数据完整性和类型正确性
  if (!payload || typeof payload !== "object") {
    wx.hideLoading();
    this.setData({ isLoading: false });
    wx.showToast({ title: "参数错误", icon: "error", duration: 2000 });
    return;
  }

  const { amount, id} = payload;//接受订单Id
  if (
    typeof amount !== "number" ||
    !Number.isInteger(amount) ||
    amount <= 0 ||!id//校验订单ID存在
  ) {
    wx.hideLoading();
    this.setData({ isLoading: false });
    wx.showToast({ title: "参数校验失败", icon: "error", duration: 2000 });

    return;
  }

  // 获取用户id
  const userId = wx.getStorageSync("userId");

  // 使用封装的请求方法发送创建订单请求（自动携带 Authorization Token）
  request("/wxpay/jsapi/createOrder/" + userId, payload, "POST")
    .then((resp) => {
      // 输出完整响应数据到控制台，便于调试
      console.log("创建订单响应:", resp);
      // 封装微信支付参数
      const params = {
        nonceStr: resp.data.nonceStr,
        package: resp.data.package,
        signType: resp.data.signType,
        paySign: resp.data.paySign,
        timeStamp: resp.data.timeStamp,


      };

      // 调用微信支付方法
      callWxService(params,id,callback);//传递Id和回调

      // 隐藏加载提示，重置加载状态
      wx.hideLoading();
      this.setData({ isLoading: false });
    })
    .catch((err) => {
      console.error("创建订单失败:", err);
      wx.hideLoading();
      this.setData({ isLoading: false });
      wx.showToast({ title: "下单失败", icon: "error", duration: 2000 });
    });
}

//创建一个方法像微信官方发送请求
export function callWxService(params,orderId,callback) {
  wx.requestPayment({
    timeStamp: params.timeStamp,
    nonceStr: params.nonceStr,
    package: params.package,
    signType: params.signType,
    paySign: params.paySign,
    success(res) {
      console.log("支付成功:", res);
      callback(true,orderId)
      wx.showToast({
        title: "支付成功",
        icon: "success",
        duration: 2000,
      });
 
    },
    fail(err) {
      console.error("支付失败:", err);
      wx.showToast({
        title: "支付失败",
        icon: "error",
        duration: 2000,
      });
    },
  });

  

}

